package com.atguigu.gmall.user.controller;

import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.model.user.UserAddress;
import com.atguigu.gmall.model.user.UserInfo;
import com.atguigu.gmall.user.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/user/passport")
public class UserInfoAPIController {
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private RedisTemplate redisTemplate;

    //提交表单
    @PostMapping("/login")
    public Result login(@RequestBody UserInfo userInfo) {
        //0 校验用户名或密码不能为空 null或是"" " "
        //1 校验用户名密码是否正确
        userInfo = userInfoService.login(userInfo);
        //1.1 成功
        if (null != userInfo) {
            //2 保存用户信息到Redis缓存中
            String token = UUID.randomUUID().toString();
            redisTemplate.opsForValue().set(RedisConst.USER_LOGIN_KEY_PREFIX + token,
                    userInfo.getId().toString(), RedisConst.USERKEY_TIMEOUT, TimeUnit.SECONDS);
            //3 颁发令牌 昵称
            Map map = new HashMap<>();
            map.put("token", token);
            map.put("nickName", userInfo.getNickName());
            //返回的数据已经被放到了Cookie中
            return Result.ok(map);
        } else {
            //1.2 失败
            return Result.fail().message("用户的账户或密码不正确!");
        }
    }

    //退出登录
    @GetMapping("/logout")
    public Result logout() {
        return Result.ok();
    }

    //查询收货地址
    //TODO 订单微服务写拦截器
    @GetMapping("/getUserAddressList")
    public List<UserAddress> getUserAddressList(HttpServletRequest request) {
        String userId = AuthContextHolder.getUserId(request);
        return userInfoService.getUserAddressList(userId);
    }
}
